package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Oplog;
import com.ldk.framework.service.IOplogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.entity.Dict;
import com.ldk.framework.entity.Dictdata;
import com.ldk.framework.service.IDictService;
import com.ldk.framework.service.IDictdataService;

@Controller
@RequestMapping("/dictdata")
public class DictDataController extends BaseController {

	/**
	 * 路由地址
	 */
	private final String route = "dictdata";
	/**
	 * 模块名称
	 */
	private final String module = "字典数据";

	@Autowired
	private IDictdataService dictDataService;
	@Autowired
	private IDictService dictService;

	@RequestMapping("/list")
	//public ModelAndView list(@RequestParam(value = "dictId", required = false, defaultValue = "0") Integer dictId,ModelMap map) {
	public ModelAndView list(@RequestParam(value = "dictId", required = false, defaultValue = "0") Integer dictId,
							 ModelMap map,HttpServletRequest request,
							 HttpServletResponse response) {
		//session是否过期
		this.isExpired(request,response);
		if (this.getRoleId(request) == 6) {
			setLinks(map, "", "", module + "管理", "/" + route + "/list", ""
					+ module, "");
		} else {
			setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加"
					+ module, "/" + route + "/add");
		}

		map.addAttribute("dictId", dictId);
		map.addAttribute("route", route);
		map.addAttribute("dictList", getDictList());

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/dictdata/listdictdata_sj");
		} else {
			return new ModelAndView("/dictdata/listdictdata");
		}
	}

	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<Dictdata> getList(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
			@RequestParam(value = "dictId", required = false, defaultValue = "0") Integer dictId,
			@RequestParam(value = "dataName", required = false, defaultValue = "") String dataName,
			HttpServletRequest request) {
		int limit = pageSize;
		int offset = (page - 1) * pageSize;

		Dictdata query = new Dictdata();
		query.setEnabled(null);
		if (dictId > 0) {
			query.setDictId(dictId);
		}
		if (!StringUtils.isBlank(dataName)) {
			query.setDataName(dataName);
		}
		Sort sort = new Sort(Direction.ASC, "dict_id");
		CustomPageable pageable = new CustomPageable(offset, limit, sort);

		Page<Dictdata> result = dictDataService.selectPageList("", query,
				pageable);

		LigerUIGridResult<Dictdata> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();

		return grid;
	}

	@RequestMapping("/add")
	public ModelAndView add(@RequestParam(value = "dictId", required = false, defaultValue = "0") int dictId,
			ModelMap map,HttpServletRequest request,
							HttpServletResponse response) {
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/"
				+ route + "/add", "", "");
		setForm(map, "/" + route + "/insert", null);
		map.addAttribute("dictList", getDictList());

		Dictdata model = new Dictdata();
		model.setDictId(dictId);

		return new ModelAndView("/dictdata/dictdatainfo", "model", model);
	}

	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable int id, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response) {
		//session是否过期
		this.isExpired(request,response);
		Dictdata query = new Dictdata();
		query.setDataId(id);
		
		Dictdata model = dictDataService.selectByKey("", query);
		if (model == null) {
			return new ModelAndView("redirect:/" + route + "/list");
		}
		setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/"
				+ route + "/edit/" + id, "", "");
		setForm(map, "/" + route + "/update", null);
		map.addAttribute("dictList", getDictList());

		return new ModelAndView("/dictdata/dictdatainfo", "model", model);
	}

	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") Dictdata model,
			RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response) {
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		try {

			Dictdata query = new Dictdata();
			query.setEnabled(null);
			query.setDataName(model.getDataName());
			query.setDictId(model.getDictId());

			Dictdata dictData = dictDataService.selectOne("", query);
			if (dictData != null) {
				rst.AddError("数据字典数据名称已经存在");
				return new ModelAndView("redirect:/" + route + "/add");
			}

			if (model.getEnabled() == null) {
				model.setEnabled(false);
			}
			//操作日志
			this.insertOplog(request,module,"","","添加"+model.getDataName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			int row = dictDataService.insert("", model);

			if (row > 0) {
				rst.AddOk("添加" + module + "成功");
			} else {
				rst.AddError("添加" + module + "失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			rst.AddError("添加" + module + "失败，失败原因：" + e.getMessage());
		}

		return new ModelAndView("redirect:/" + route + "/add");
	}

	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") Dictdata model,
			RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response) {
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();

		redAttr.addAttribute("id", model.getDataId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

		try {
			Dictdata query = new Dictdata();
			query.setEnabled(null);
			query.setDataName(model.getDataName());
			query.setDictId(model.getDictId());

			Dictdata dictData = dictDataService.selectOne("", query);
			if (dictData != null && dictData.getDataId() != model.getDataId()) {
				rst.AddError("数据字典数据名称已经存在");
				return new ModelAndView("redirect:/" + route + "/add");
			}
			if (model.getEnabled() == null) {
				model.setEnabled(false);
			}
			//操作日志
			this.insertOplog(request,module,"","","修改"+model.getDataName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			int row = dictDataService.updateByKey("", model);
			if (row > 0) {
				rst.AddOk("修改" + module + "成功");
			} else {
				rst.AddError("修改" + module + "失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			rst.AddError("修改" + module + "失败，失败原因：" + e.getMessage());
		}

		return new ModelAndView("redirect:/" + route + "/edit/{id}");
	}

	@ResponseBody
	@RequestMapping("/remove/{id}")
	public ResponseResult remove(@PathVariable int id, HttpServletRequest request) {

		ResponseResult rst = new ResponseResult();
		if (id < 1) {
			rst.AddError("删除" + module + "错误");
		}
		Boolean successed = false;
		try {
			Dictdata query = new Dictdata();
			query.setDataId(id);
			Dictdata dictdata = dictDataService.selectByKey("", query);
			this.insertOplog(request,module,"","","删除:"+dictdata.getDataName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
			int row = dictDataService.deleteByKey("", query);
			successed = row > 0;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (successed) {
			rst.AddOk("删除" + module + "成功");
		} else {
			rst.AddError("删除" + module + "失败");
		}

		return rst;
	}
	
	protected List<Dict> getDictList() {
		Dict query = new Dict();
		query.setEnabled(true);
		
		return dictService.selectList("", query);
	}
}
